Page({
  data: {
    userAddress: {},
    cart: [],
    allChecked: false,
    //商品总数量
    totalPrice: 0,
    // 商品总价格
    totalNum: 0
  },
  onShow() {
    const userAddress = wx.getStorageSync("res")
    // 获取缓存中的购物车数据
    const cart = wx.getStorageSync("cart") || []
    this.setData({
      userAddress
    })
    this.setCart(cart)
  },
  //点击收货按钮
  handelChoose() {
    wx.chooseAddress({
      success(res) {
        wx.setStorageSync("res", res)
      }
    })
  },
  handeItemChange(e) {
    // 获取商品Id
    const goods_id = e.currentTarget.dataset.id
    // 获取购物车数组
    let { cart } = this.data
    // 找到被修改的商品对象
    let index = cart.findIndex(v => v.goods_id === goods_id);
    // 选中状态取反
    cart[index].checked = !cart[index].checked
    this.setCart(cart)
  },
  // 封装购物车计算功能
  setCart(cart) {
    // 计算全选
    let allChecked = true
    // 商品总价格
    let totalPrice = 0
    // 商品总数量
    let totalNum = 0
    cart.forEach((v) => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price
        totalNum += v.num
      } else {
        allChecked = false
      }
    })
    allChecked = cart.length != 0 ? allChecked : false
    this.setData({
      cart,
      totalPrice,
      totalNum,
      allChecked
    })
    wx.setStorageSync('cart', cart);
  },
  // 全选反选
  handelItemAllChecked() {
    // 获取data中的数据
    let { cart, allChecked } = this.data
    // 修改
    allChecked = !allChecked;
    cart.forEach(v => v.checked = allChecked)
    // 修改完毕，重新保存到dada
    this.setCart(cart)
  },
  // 购物车加减
  jian(e) {
    const { num } = e.currentTarget.dataset
    // 获取点击的下标
    const { index } = e.currentTarget.dataset
    const cart = this.data.cart
    // 改变this指向
    const that = this
    if (Number(num) === 1) {
      cart[index].num++
    } else {
      if (cart[index].num === 1) {
        wx.showModal({
          title: '提示',
          content: '是否删除该商品?',
          success(res) {
            if (res.confirm) {
              cart.splice(index, 1)
              that.setCart(cart)
            }
          }
        })
      } else {
        cart[index].num--
      }
    }
    this.setCart(cart)
  },
  // 结算功能
  handelPay() {
    // 判断是否有商品
    const cart = this.data.cart
    const { userAddress } = this.data
    if (cart.length === 0) {
      wx.showToast({
        title: '请选择商品!',
        icon: 'none',
        duration: 2000
      })
    } else if (!userAddress) {
      wx.showToast({
        title: '请选择收货地址!',
        icon: 'none',
        duration: 2000
      })
    } else {
      // 动态跳转到支付页面
      wx.navigateTo({
        url: '../pay/index'
      })
    }
  }
})